/*
 *   This File is Part of CuteOgre Game Engine
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *	Copyright 2010 Alexandre Pires ( c.alexandre.pires@gmail.com )
 *  Created on: 2010/09/04
 */


#include "Gui/StyleSheetManager.h"
#include "Gui/StyleSheet.h"
#include "LogManager.h"
#include "ConfigManager.h"
#include <QStringList>
#include "OGRE/OgreResourceManager.h"

template<> StyleSheetManager* Singleton<StyleSheetManager>::ms_Singleton = 0;

StyleSheetManager::~StyleSheetManager () {

	foreach ( StyleSheet* stylesheet, mStyleSheets )
			delete stylesheet;

	mStyleSheets.clear();
}

void StyleSheetManager::init () {

	if ( !mShutdown )
		return;

	LogManager::message("StyleSheetManager::Starting up");

	QString str = ConfigManager::readString ( "StylesPath", "Data/Styles;" );

	if ( str.endsWith(';') )
		str.chop(1);

	QStringList urls = str.split ( ';' );

	Ogre::ResourceGroupManager* mngr =
			&Ogre::ResourceGroupManager::getSingleton ();

	foreach ( QString url, urls )
			mngr->addResourceLocation ( url.toStdString(), "FileSystem", "StyleSheets" );

	mShutdown = false;
}

void StyleSheetManager::shutdown () {

	if ( mShutdown )
		return;

	LogManager::message("StyleSheetManager::Shutting down");

	foreach ( StyleSheet* styleSheet, mStyleSheets )
		delete styleSheet;

	mStyleSheets.clear();

	mShutdown = true;
}

void StyleSheetManager::load ( const QString& rName ) {

	LogManager::message(QString("StyleSheetManager::Loading stylesheet %1").arg(rName) );

	if ( exists( rName) ) {
		mStyleSheets[rName]->reload();
		return;
	}

	mStyleSheets[rName] = new StyleSheet(rName);
}


StyleSheet* StyleSheetManager::getStyleSheet ( const QString& rName ) {

	if ( mStyleSheets.find(rName) == mStyleSheets.end() ) {
		LogManager::message(QString("StyleSheetManager::Couldn't find StyleSheet %1!").arg(rName));
		return NULL;
	}

	return mStyleSheets[rName];
}
